<template>
    <div class>
      <div class="card tr mb2">
        <el-tooltip content="显示字段筛选" placement="bottom" effect="light">
          <el-popover placement="bottom" width="200" trigger="click">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
            </el-checkbox>
            <el-checkbox-group v-model="showItemList" @change="handleCheckedChange">
              <el-checkbox v-for="(item,key) in allItemList" :key="key" :label="item">{{item.name}}</el-checkbox>
            </el-checkbox-group>
            <el-button slot="reference" icon="el-icon-menu" size="mini" type="primary" circle></el-button>
          </el-popover>
        </el-tooltip>
        <el-tooltip content="展开/收起表单" placement="bottom" effect="light">
          <el-button icon="el-icon-search" @click="formShow= !formShow" size="mini" type="primary" circle></el-button>
        </el-tooltip>
        <el-tooltip content="下载当前表格数据" placement="bottom" effect="light">
          <el-button icon="el-icon-download" @click="handleDownload" size="mini" type="primary" circle></el-button>
        </el-tooltip>
        <el-button size="mini" type="primary" icon="el-icon-plus" @click="showDialog">创建</el-button>
      </div>
      <div class="card" v-show="formShow">
        <el-form size="mini" :style="style" :model="ruleForm" ref="ruleForm" inline label-width="100px"
          class="demo-ruleForm">
          <el-form-item label="表名" prop="geneName" style="width:300px">
            <!-- <el-input size="mini" v-model="codeForm.tableName" style="width:200px"></el-input> -->
            <template>
              <el-select v-model="ruleForm.geneName" clearable filterable style="width:200px" placeholder="请选择">
                <el-option
                  v-for="item in tableNameList"
                  :key="item.tableName"
                  :label="item.tableName"
                  :value="item.tableName">
                </el-option>
              </el-select>
            </template>
          </el-form-item>
          <my-form-item>
            <el-button size="mini" type="primary" @click="submitForm('ruleForm')">查询</el-button>
            <el-button size="mini" @click="resetForm('ruleForm')">重置</el-button>
          </my-form-item>
        </el-form>
      </div>
      <el-table stripe :data="tableData" border style="width: 100%">
        <el-table-column type="index" width="60px" align="center" fixed="left" label="序号"></el-table-column>
        <el-table-column v-for="(item,index) in showItemList" align="center" :width="item.width || '' " :key="index" :label="item.name" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <template v-if="!item.formatter">{{ scope.row[item.key] }}</template>
            <template v-else>
              <span v-text="item.formatter(scope.row, item)"></span>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="downLoadCode(scope.$index, scope.row)">下载代码</el-button>
            <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-card style="text-align:right;">
        <el-pagination @size-change="sizeChange" @current-change="currentChange" :current-page="currentPage"
          :page-sizes="[ 10, 20,30, 40]" :page-size="pageSize" background layout="total, sizes, prev, pager, next"
          :total="total"></el-pagination>
      </el-card>
      <!-- --------------------------------------------------------添加弹出框 -->
      <el-dialog title="新增管理" width="80%" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
          <CodeDev @fatherInit="fatherInit"></CodeDev>
      </el-dialog>
      <!-- --------------------------------------------------------编辑弹出框 -->
      <el-dialog title="编辑管理" :visible.sync="dialogEditVisible" :close-on-click-modal="false">
        <el-form size="mini" :style="style" :model="editForm" ref="editForm" :rules="rules" inline label-width="100px"
          class="demo-ruleForm">
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="dialogEditVisible = false">取 消</el-button>
          <el-button size="mini" type="primary" @click="handleEdit()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
    const defaultFormThead = [
      { key: "geneName", name: "表名",width:'160px' },
      { key: "geneType", name: "类型",width:'120px',
       formatter: row => {
      if (row.geneType == 1) {
        return "单表生成";
       } else {
         return "主从表生成";
      }
     }
      
      },
      { key: "osType", name: "操作类型",width:'100px' },
      { key: "dbType", name: "数据库类型",width:'120px' },
      { key: "createUserName", name: "创建人",width:'100px' },
      { key: "createTime", name: "生成时间",width:'160px' },
      { key: "projectPath", name: "后台代码路径",width:'200px' },
      { key: "uiPath", name: "前端代码路径",width:'200px' },
      // { key: "serverName", name: "生成服务名",width:'120px' },
      // { key: "serverIp", name: "生成服务的ip",width:'120px' },
      ];
    import EnumSelector from '@/pages/comm/enumSelector'
    import CodeDev from '@/pages/biz/code/codeDev'
    export default {
      components: { EnumSelector,CodeDev },
      data() {
        return {
          tableNameList:[],
          checkAll: true,
          isIndeterminate: false,
          allItemList: defaultFormThead,
          showItemList: defaultFormThead,
          formShow: false,
          dialogFormVisible: false,
          dialogEditVisible: false,
          offForm: true, //是否折叠
          folding: false, //表单是否超过一行
          formLabelWidth: "80px",
          tableData: [],
          total: 0,
          pageSize: 10,
          currentPage: 1,
          ruleForm: {
            geneName: '',
        },
      style: {},
      rules: {
        },
    addForm: {
        },
    editForm: {
        }
      };
    },
  
    mounted() {
      this.getTableNameList();
      this.init();
      let formHeight = this.$refs.ruleForm.$el.clientHeight;
      if (formHeight > 62) {
        this.folding = true;
        this.style = {
          height: "62px",
          overflow: "hidden"
        };
      } else {
        this.folding = false;
        this.style = {
          height: "auto",
          overflow: "hidden"
        };
      }
    },
    computed: {
    },
    watch: {
      offForm: function(v) {
        if (v) {
          this.style = {
            height: "62px",
            overflow: "hidden"
          };
        } else {
          this.style = {
            height: "auto",
            overflow: "hidden"
          };
        }
      }
    },
    methods: {
      fatherInit(){
        this.dialogFormVisible = false;
        this.init();
      },
      getTableNameList(){
      this.$api
              .formPost("/api/code/codeTableInfo/getTableNameList", {
              })
              .then(res => {
                  if (res.retHead.code == "0000000") {
                      this.tableNameList=res.retBody;
                  }
              });
     },
      handleDownload() {
        this.downloadLoading = true;
        import("@/vendor/Export2Excel").then(excel => {
          const tHeader = [
            "id",
            "表名",
            "类型（1，单表，2，主从表）",
            "生成后台代码路径+时间",
            "生成前端代码路径+时间",
            "操作类型，windows，和linux",
            "生成服务名",
            "生成服务的ip",
            "数据库类型",
            "生成人姓名",
            "生成人id",
            "生成时间",
                      ];
          const filterVal = [
            "id",
            "geneName",
            "geneType",
            "projectPath",
            "uiPath",
            "osType",
            "serverName",
            "serverIp",
            "dbType",
            "createUserName",
            "createUserId",
            "createTime",
                      ];
          const data = this.formatJson(filterVal, this.tableData);
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: "table-list"
          });
          this.downloadLoading = false;
        });
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v =>
          filterVal.map(j => {
            if (j === "timestamp") {
              return parseTime(v[j]);
            } else {
              return v[j];
            }
          })
        );
      },
      handleCheckedChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === defaultFormThead.length;
        this.isIndeterminate =
          checkedCount > 0 && checkedCount < defaultFormThead.length;
      },
      handleCheckAllChange(val) {
        this.showItemList = val ? defaultFormThead : [];
        this.isIndeterminate = false;
      },
      sizeChange(n) {
        this.pageSize = n;
        this.init();
      },
      currentChange(n) {
        this.currentPage = n;
        this.init();
      },
      init() {
        let searchForm = {};
          searchForm.geneName=this.ruleForm.geneName;
          let params = {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            ...searchForm
          };
        this.$api
          .formPost("/api/code/geneRecord/doGetList", params)
          .then(res => {
            if (res.retHead.code == "0000000") {
              this.tableData = res.retBody.list;
              this.total = res.retBody.total;
              this.currentPage = res.retBody.pageNum;
            }
          });
      },
      showDialog() {
        this.dialogFormVisible = true;
      },
      downLoadCode(index, row) {
          let id=row.id;
          window.location.href= process.env.baseURL+"/api/code/geneRecord/doDownLoad?Auth-User-Token="+
          sessionStorage.getItem("token")+
          "&id="+encodeURI(id);
      },
    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$api
            .formPost("/api/code/geneRecord/doRmById", {
              id: row.id
            })
            .then(res => {
              if (res.retHead.code == "0000000") {
                this.$message({
                  message: "操作成功！",
                  type: "success"
                });
                this.init();
              } else {
                this.$message({
                  message: "操作失败！",
                  type: "error"
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    submitForm(formName) {
      this.init();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
    },
    created() { }
  };
  </script>
  <style lang='scss' scoped>
    .btns {
      text-align: right;
    }
  
    .icon-arrow {
      position: absolute;
      bottom: 5px;
      left: 0;
      width: 100%;
      height: 1px;
      background-color: #f1f1f1;
  
      i {
        background-color: #fff;
        position: absolute;
        color: #999;
        bottom: -7px;
        margin-left: 50%;
        transform: translateX(-50%);
        cursor: pointer;
      }
    }
  </style>